﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-04-03 16:13:22Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

using Foundation;
using Outcoder.Concurrency;

namespace Outcoder
{
	public partial class UISynchronizationContext : ISynchronizationContext
	{
		readonly NSObject nsObject = new NSObject();

		void EnsureInitialized()
		{

		}

		public void InvokeWithoutBlocking(SendOrPostCallback callback, object state,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(callback, "callback");

			EnsureInitialized();

			var invokableCallback = GetWrappedCallback(callback, state, memberName, filePath, lineNumber);

			InvokeOnMainThread(() => invokableCallback(state));
		}

		public void InvokeWithoutBlocking(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");

			EnsureInitialized();

			Action invokableAction = GetWrappedAction(action, memberName, filePath, lineNumber);

			BeginInvokeOnMainThread(invokableAction);
		}

		public void InvokeAndBlockUntilCompletion(SendOrPostCallback callback, object state,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(callback, "callback");
			EnsureInitialized();

			var invokableCallback = GetWrappedCallback(callback, state, memberName, filePath, lineNumber);

			InvokeOnMainThread(() => invokableCallback(state));
		}

		public void InvokeAndBlockUntilCompletion(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

			Action invokableAction = GetWrappedAction(action, memberName, filePath, lineNumber);

			InvokeOnMainThread(invokableAction);
		}

		public void InvokeIfRequired(Action action,
			[CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

			Action invokableAction = GetWrappedAction(action, memberName, filePath, lineNumber);

			BeginInvokeOnMainThread(invokableAction);
		}

		public async Task InvokeIfRequiredAsync(
			Func<Task> action, [CallerMemberName]string memberName = null,
			[CallerFilePath]string filePath = null,
			[CallerLineNumber]int lineNumber = 0)
		{
			ArgumentValidator.AssertNotNull(action, "action");
			EnsureInitialized();

			Func<Task> invokableAction = GetWrappedAction(action, memberName, filePath, lineNumber);

			if (Thread.CurrentThread.IsBackground)
			{
				BeginInvokeOnMainThread(() => invokableAction());
			}
			else
			{
				await invokableAction();
			}
		}

		void BeginInvokeOnMainThread(Action action)
		{
			nsObject.BeginInvokeOnMainThread(() => action());
		}

		void InvokeOnMainThread(Action action)
		{
			nsObject.InvokeOnMainThread(() => action());
		}

		public bool InvokeRequired { get; private set; }

		public void Initialize()
		{
			/* Intentionally left blank. */
		}

		#region Singleton implementation

		UISynchronizationContext()
		{
		}

		public static UISynchronizationContext Instance
		{
			get
			{
				return Nested.instance;
			}
		}

		class Nested
		{
			// Explicit static constructor to tell C# compiler
			// not to mark type as beforefieldinit
			static Nested()
			{
			}

			internal static readonly UISynchronizationContext instance = new UISynchronizationContext();
		}

		#endregion

		#region InvokedExceptionHandler
		InvokedExceptionHandler invokedExceptionHandler;

		public InvokedExceptionHandler InvokedExceptionHandler
		{
			get
			{
				return invokedExceptionHandler;
			}
			set
			{
				invokedExceptionHandler = value;
			}
		}

		SendOrPostCallback GetWrappedCallback(SendOrPostCallback callback, object state,
			string memberName = null,
			string filePath = null,
			int lineNumber = 0)
		{
			if (invokedExceptionHandler == null)
			{
				return callback;
			}

			SendOrPostCallback wrappedCallback = delegate
			{
				try
				{
					callback.Invoke(state);
				}
				catch (Exception ex)
				{
					var args = new InvokedExceptionArgs(memberName, filePath, lineNumber, ex);
					bool handled = invokedExceptionHandler(this, args);

					if (!handled)
					{
						throw;
					}
				}
			};

			return wrappedCallback;
		}

		Action GetWrappedAction(Action action,
			string memberName = null,
			string filePath = null,
			int lineNumber = 0)
		{
			if (invokedExceptionHandler == null)
			{
				return action;
			}

			Action invokableAction = delegate
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					var args = new InvokedExceptionArgs(memberName, filePath, lineNumber, ex);
					bool handled = invokedExceptionHandler(this, args);

					if (!handled)
					{
						throw;
					}
				}
			};

			return invokableAction;
		}

		Func<Task> GetWrappedAction(Func<Task> action,
			string memberName = null,
			string filePath = null,
			int lineNumber = 0)
		{
			if (invokedExceptionHandler == null)
			{
				return action;
			}

			Func<Task> invokableAction = async () =>
			{
				try
				{
					await action();
				}
				catch (Exception ex)
				{
					var args = new InvokedExceptionArgs(memberName, filePath, lineNumber, ex);
					bool handled = invokedExceptionHandler(this, args);

					if (!handled)
					{
						throw;
					}
				}
			};

			return invokableAction;
		}
		#endregion

	}
}
